package com.bilibili.juc.cf.one;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class GatherCompletableFutureResultsExample2 {
    public static void main(String[] args) {
        // 创建多个 CompletableFuture<String> 任务
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Result 1");
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Result 2");
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "Result 3");

        List<CompletableFuture<String>> futures = List.of(future1, future2, future3);

        // 合并所有结果到 List<String>
        CompletableFuture<List<String>> combinedFuture = CompletableFuture.completedFuture(new ArrayList<>());
        for (CompletableFuture<String> future : futures) {
            combinedFuture = combinedFuture.thenCombine(future, (list, result) -> {
                list.add(result);
                return list;
            });
        }

        // 获取最终结果
        List<String> results = combinedFuture.join();
        System.out.println(results); // 输出: [Result 1, Result 2, Result 3]
    }
}